﻿using System;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Project;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using PowerGui.AddOn;
using PowerGui.AddOn.Interfaces;
using PowerGuiVsx.Interfaces;

namespace PowerGUIVsx.Project
{
    public class PowerShellProjectConfig : ProjectConfig
    {
        private readonly PowerGuiVsxPackage _package;

        [Import]
        public IDebugger Debugger { get; set; }


        [Import]
        public IDebuggerLauncher DebuggerLauncher { get; set; }

        public PowerShellProjectConfig(PowerGuiVsxPackage package, ProjectNode project, string configuration) : base(project, configuration)
        {
            PowerGuiComposer.Compose(this, false);

            _package = package;
        }

        public override int DebugLaunch(uint grfLaunch)
        {
            var parameters = ProjectMgr.GetProjectProperty("DebugParameters");

            if (grfLaunch == 4)
            {
                 Debugger.ExecuteNoDebug(parameters);   
            }
            else
            {
                var debugger = _package.GetService(typeof(SVsShellDebugger)) as IVsDebugger;
                var shell = _package.GetService(typeof(SVsUIShell)) as IVsUIShell;

                DebuggerLauncher.LaunchDebugger(shell, debugger, _package.EditorFactory, (int)grfLaunch, parameters);
            }

            ShowToolWindow();

            return VSConstants.S_OK;
        }



        private void ShowToolWindow()
        {
            // Get the instance number 0 of this tool window. This window is single instance so this instance
            // is actually the only one.
            // The last flag is set to true so that if the tool window does not exists it will be created.
            ToolWindowPane window = _package.FindToolWindow(typeof(InputOutputToolWindow), 0, true);
            if ((null == window) || (null == window.Frame))
            {
                throw new NotSupportedException("Cannot create window!");
            }

            IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
        }

        public override int QueryDebugLaunch(uint flags, out int fCanLaunch)
        {
            fCanLaunch = 1;
            return VSConstants.S_OK;
        }
    }
}
